package com.lqd.mall.system.controller;

import com.google.code.kaptcha.Producer;
import com.lqd.mall.basis.code.CommonCode;
import com.lqd.mall.basis.constant.Constants;
import com.lqd.mall.basis.response.Result;
import com.lqd.mall.basis.utils.sign.Base64;
import com.lqd.mall.basis.utils.uuid.IdUtils;
import com.lqd.mall.common.CaptchaControllerApi;
import com.lqd.mall.log.annotation.Log;
import com.lqd.mall.redis.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 零起点
 * @create 2022-02-12 22:24
 */
@RestController
public class CaptchaController implements CaptchaControllerApi {

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisUtils redisUtils;

    // 验证码类型
    @Value("${mall.captchaType}")
    private String captchaType;


    @Override
    public Result<Map<String, Object>> getCode(HttpServletResponse response) throws IOException {
        Result<Map<String, Object>> result = new Result<>();
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        }
        else if ("char".equals(captchaType))
        {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisUtils.set(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return result.FAIL(new HashMap<String, Object>());
        }

        Map<String, Object> ajax = new HashMap<>();
        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return result.SUCCESS(ajax);
    }
}
